/**
 * echarts自动轮播item
 * @param chart echarts实例
 * @param dataArr 数据数组  有多少个项
 * @returns
 */
export const setAutoHoverIntervalFun = (
  chart: echarts.ECharts,
  dataArr: string[] | any[]
) => {
  let curIndex = 0
  // timer没必要过分注意类型，做的话安装@types/node
  let timer: any
  const getCurIndex = () => {
    return curIndex
  }
  const setCurIndex = (index: number) => {
    curIndex = index
    run()
  }
  // 初始化 调用run
  const init = () => {
    run()
    mouseOverFun()
  }
  // 启动定时器
  const run = () => {
    if (!chart) {
      console.warn('echart未传入或未初始化！')
    }
    if (timer) {
      clearInterval(timer)
    }
    timer = setInterval(() => {
      setAutoHover(chart, curIndex, dataArr)
      curIndex++
      if (curIndex >= dataArr.length) {
        curIndex = 0
      }
    }, 2000)
  }
  // 鼠标移入
  const mouseOverFun = () => {
    if (!chart) {
      console.warn('echart未传入或未初始化！')
    }
    chart?.on('mousemove', (ev: any) => {
      const { dataIndex } = ev as { dataIndex: number }
      setCurIndex(dataIndex)
      run()
    })
  }

  const stop = () => {
    if (timer) {
      clearInterval(timer)
    }
  }
  return {
    init,
    getCurIndex,
    setCurIndex,
    run,
    mouseOverFun,
    stop
  }
}
export const setAutoHover = (
  chart: echarts.ECharts,
  index: number,
  dataArr?: string[] | any[]
) => {
  chart.dispatchAction({
    type: 'downplay',
    seriesIndex: 0, //serieIndex的索引值   可以触发多个
    dataIndex: index - 1 >= 0 ? index - 1 : (dataArr?.length || 1)! - 1
  })
  chart.dispatchAction({
    type: 'highlight',
    seriesIndex: 0,
    dataIndex: index
  })
  chart.dispatchAction({
    type: 'showTip',
    seriesIndex: 0,
    dataIndex: index
  })
}
